<template>
  <div>
    <div class="divCreate" v-if="type == 'input'">
      <input type="text" v-maxLen="maxLength" v-model="ipt" />
      <span class="span">0/{{maxLength}}</span>
    </div>
    <div class="divCreate" v-else-if="type == 'textarea'">
      <textarea
        v-maxLen="maxLength"
        v-model="ipt"
        cols="30"
        rows="10"
      ></textarea>
      <span class="spanTextarea">0/{{ maxLength }}</span>
    </div>
  </div>
</template>

<script>
export default {
  props:{
    type:{
      default:'input',
      type:String,
    },
    maxLength:{
      default:10,
      type:[String,Number]
    }
  },
  data(){
    return {
      ipt:'',
    }
  },
  directives:{
    maxLen :{
      inserted(el, binding) {
        el.setAttribute("maxLen", binding.value);
      },
      update(el, binding) {
        let iptLen = el.value.length;
        let span = el.nextElementSibling;
        span.innerHTML = iptLen + "/" + binding.value;
        if (iptLen == binding.value) {
          el.style.color = "coral";
        } else {
          el.style.color = "";
        }
      },
    }
  }
};
</script>

<style  scoped>
.divCreate {
  position:relative;
  display:inline-block;
}

.span {
  position: absolute;
  top: 5px;
  right: 3px;
  font-size: 10px;
  color: #999;
}

.spanTextarea {
   position: absolute;
  bottom: 8px;
  right: 5px;
  font-size: 10px;
  color: #999;
}

</style>